﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Net.Sockets;

namespace EncryptionServer.CrcCheck.CrcThread
{
    class ThreadCrc
    {
        //属性
        public Socket S { get; set; }
        public FrmCRCCheck frm { get; set; }
        public DataAccess.DalData Dal { get; set; }
        /// <summary>
        /// 正在开单，还未保存的产品照片CRC码集合
        /// </summary>
        public List<int> TempCrc = new List<int>();
        public void Start()
        {
            try
            {
                while (true)
                {
                    byte[] bytes = new byte[1024];
                    byte[] result = null;
                    int len = S.Receive(bytes);
                    if (len == 0)
                    {
                        try
                        {
                            S.Close();
                            Thread.CurrentThread.Abort();
                        }
                        catch (Exception ex)
                        {
                            if (ex is ThreadAbortException)
                            {

                            }
                        }
                    }
                    string path = System.Text.Encoding.Unicode.GetString(bytes, 0, len);        //照片全路径
                    //new%%%新增产品；delete%%%删除产品；save%%%保存订单
                    //int index = path.IndexOf("%%%");
                    string[] paths = path.Split(new string[] { "%%%" }, StringSplitOptions.RemoveEmptyEntries);
                    string type = paths[0];
                    string photoPath = null;
                    if (paths.Count() > 1)                  //save操作没有照片路径
                        photoPath = paths[1];            //如果有多个照片路径，这里只取第一个，就不会出错          
                    if (type == "new")
                    {
                        result = new byte[8];
                        byte[] photo = File.ReadAllBytes(photoPath);
                        int crcCode = Crc32.GetCRC32(photo);
                        string crcMsg = null;
                        if (FrmCRCCheck.ListCrc.Contains(crcCode) || TempCrc.Contains(crcCode))         //crc码存在
                        {
                            result = System.Text.Encoding.Unicode.GetBytes("0");                    //0表示存在 1表示不存在 2表示crc码保存进数据库成功 3表示crc码保存进数据库失败
                            crcMsg = "“" + photoPath + "”已校验，该照片在最近2天内已开过单";
                        }
                        else
                        {
                            result = System.Text.Encoding.Unicode.GetBytes("1");
                            crcMsg = "“" + photoPath + "”已校验";
                        }
                        S.Send(result);
                        TempCrc.Add(crcCode);           //保存进临时CRC集合中
                        frm.Invoke(frm.InvokeShowCrcMsg, crcMsg);
                    }
                    else if (type == "delete")
                    {
                        byte[] photo = File.ReadAllBytes(photoPath);
                        int crcCode = Crc32.GetCRC32(photo);
                        if (TempCrc.Contains(crcCode))
                        {
                            TempCrc.Remove(crcCode);
                        }
                    }
                    else if (type == "save")
                    {
                        if (TempCrc.Count > 0)
                        {
                            try
                            {
                                Dal.SaveCrc(TempCrc);
                                FrmCRCCheck.ListCrc.AddRange(TempCrc);
                            }
                            catch                   //如果数据库异常，就从数据库重新加载CRC集合
                            {
                                FrmCRCCheck.ListCrc = Dal.GetCrc();
                            }
                        }
                        TempCrc.Clear();
                    }
                    else if (type == "close")
                    {
                        try
                        {
                            S.Close();
                            Thread.CurrentThread.Abort();
                        }
                        catch (Exception ex)
                        {
                            if (ex is ThreadAbortException)
                            {

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (ex is SocketException)
                    {
                        SocketException se = ex as SocketException;
                        if (se.ErrorCode == 10054)                      //客户端已关闭
                        {
                            if (S.Connected)
                                S.Close();
                        }
                        try
                        {
                            Thread.CurrentThread.Abort();
                        }
                        catch { }
                    }
                    else if (ex is ThreadAbortException)
                    {

                    }
                    else
                    {
                        frm.Invoke(frm.InvokeErrorConsole, ex.Message);         //其余异常，中断程序
                    }
                }
                catch (Exception e)
                {
                    if (e is ThreadAbortException) //线程中断异常，不作处理
                    {

                    }
                    else                           //其余异常，中断程序                             
                    {
                        frm.Invoke(frm.InvokeErrorConsole, e.Message);
                    }
                }
            }
        }
    }
}
